﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FaceSharp.Api;
using FaceSharp.Api.GraphApi;
using FaceSharp.MVC.Code.Facebook;
using FaceSharp.MVC.Filters;
using Newtonsoft.Json;

namespace FaceSharp.MVC.Areas.FacebookApp.Controllers
{
    [FacebookGraphApiFilter(CanvasRedirect = true, ForceLogin = true, ResponseType = "code token")]
    public class TestController : BaseController
    {

        public ActionResult Index()
        {
            var facebookApi = new FacebookApi();
            var currentUser = facebookApi.User.GetCurrentUser();
            return View(currentUser);
        }

        public ActionResult DynamicExample()
        {
            var facebookApi = new FacebookApi();
            dynamic friends = facebookApi.GraphApi.MakeGraphRequest("me", "friends", new[] {"id", "name", "first_name", "last_name"});

            return View(friends);
        }

        public ActionResult Photos()
        {
            var facebookApi = new FacebookApi();
            if(Request.Form["AlbumId"] != null)
            {
                ViewData["Photos"] = facebookApi.Album.GetPhotos(Request.Form["AlbumId"]);
            }

            return View(facebookApi.Album.List());
        }

        public ActionResult UploadPhoto()
        {
            var facesharpLogo = Image.FromFile(Server.MapPath("/areas/facebookapp/images/logo-facesharp.gif"));
            var facebookApi = new FacebookApi();
            var albumId = (Request.Form["AlbumId"].ToString());

            try
            {
                var photoId = facebookApi.Photo.Add(albumId, "New Profile Pic", facesharpLogo, ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Message:{0} TargetSite:{1}",ex.Message,ex.TargetSite);
                throw;
            }
           
            
            return RedirectToAction("Photos");
        }
        
        public ActionResult Fql()
        {
            var facebookApi = new FacebookApi();
            ViewData["FqlQuery"] = "SELECT application_id FROM developer WHERE developer_id=" +
                                           facebookApi.User.GetCurrentUserId();
            if(!String.IsNullOrEmpty(Request["fqlString"]))
            {
                
                ViewData["FqlQuery"] = Request["fqlString"];
                ViewData["FqlResults"] = facebookApi.RestApi.ExecuteFql(Request["fqlString"]);
            }
            return View();
        }

        public ActionResult Insights()
        {
            var facebookApi = new FacebookApi();

            var appToken = facebookApi.Application.GetApplicationAccessToken();
            var appFacebookApi = new FacebookApi(appToken);
            ViewData["Insights"] = appFacebookApi.Insights.Get(long.Parse(System.Web.HttpContext.Current.Items["ApplicationId"].ToString()));
            ViewData["ApplicationToken"] = appToken;

            ViewData["AppsData"] = facebookApi.User.GetCurrentUser().Accounts.Where(x => x.Category == "Application").ToList();
            ViewData["PagesData"] = facebookApi.User.GetCurrentUser().Accounts.ToList();
            return View();
        }

        private static string UppercaseString(string inputString)
        {
            return inputString.ToUpper();
        }
        
        public void InsightsExecute()
        {
            var facebookApi = new FacebookApi();
            long appId;
            long pageId;
            if (long.TryParse(Request["PageId"], out pageId))
            {
                var account = facebookApi.User.GetCurrentUser().Accounts.FirstOrDefault(x => x.Id == pageId);
                if (account != null)
                {
                    var pageFacebookApi = new FacebookApi(account.AccessToken);

                    Func<string, string> convertMethod = UppercaseString;

                    var period = (Request["PagePeriod"] != null &&
                                  !string.IsNullOrWhiteSpace(Request["PagePeriod"].ToString(CultureInfo.InvariantCulture)))
                                     ? "/" + Request["PagePeriod"].ToString(CultureInfo.InvariantCulture)
                                     : "";
                    
                    var results = pageFacebookApi.GraphApi.BaseGraphRequest<string>(
                        Request["PageId"] + "/insights/" + Request["PageAppMetric"] + period, 
                        new Dictionary<string,string>()
                        {
                            {"since", Request["PageSince"].ToString(CultureInfo.InvariantCulture)},
                            {"until", Request["PageUntil"].ToString(CultureInfo.InvariantCulture)}
                        },
                        ((x) => x.ToString(CultureInfo.InvariantCulture))
                        ); //, "insights/" + Request["PageAppMetric"]);
                    Response.ContentType = ("application/json");
                    Response.Write(results.Results); ;
                   // return View();
                }
            }
            //else if (long.TryParse(Request["AppId"], out appId))
            //{
            //    var app = facebookApi.User.GetCurrentUser().Accounts.FirstOrDefault(x => x.Id == appId);
            //    if(app != null)
            //    {
            //        string results = string.Empty;
            //        if ((!String.IsNullOrEmpty(Request["AppSecret"])) && (!String.IsNullOrEmpty(Request["AppUrl"])))
            //        {
            //            Trace.Write("AppSecret Provided", "TestController.InsightsExecute");
            //            var appToken = facebookApi.Application.GetApplicationAccessToken(app.Id.ToString(CultureInfo.InvariantCulture), Request["AppSecret"]);
            //            var appFacebookApi = new FacebookApi(appToken);
            //            results = appFacebookApi.Insights.Get(app.Id);
            //        }
            //        else
            //        {

            //            results = facebookApi.Insights.Get(app.Id);
            //        }
            //        ViewData["Insights"] = results;
                    
            //        return View(); 
            //    }
            //}
            //return RedirectToAction("Insights");
        }

        public ActionResult Accounts()
        {
            var facebookApi = new FacebookApi();
            return View(facebookApi.User.GetCurrentUser().Accounts);
        }

        

        public ActionResult AccountSetRestriction()
        {
            if(!string.IsNullOrEmpty(Request["AccountId"]))
            {
                var facebookApi = new FacebookApi();
                var accountId = long.Parse(Request["AccountId"]);
                var account = facebookApi.User.GetCurrentUser().Accounts.FirstOrDefault(x => x.Id == accountId);
                if (account != null)
                {
                    string accessToken = account.AccessToken;
                    if (account.Category == "Application")
                    {
                        accessToken = facebookApi.Application.GetApplicationAccessToken(accountId.ToString(NumberFormatInfo.InvariantInfo), Request["AppSecret"]);
                    }
                    var core = new FacebookCore {AccessToken = accessToken};
                    var tpc = new TypedGraphClient<string>(core, (x) => x);
                    var result = tpc.MakeGraphPost(accountId.ToString(NumberFormatInfo.InvariantInfo), new Dictionary<string, string> { { "restrictions", "{\"type\":\"alcohol\"}" } });
                    if(result == "true")
                    {
                        Trace.Write("true, posted successfully");
                    }
                    
                    //dynamic accountDetails = accountFacebookApi.GraphApi.MakeGraphPost(accountId.ToString(NumberFormatInfo.InvariantInfo) +  "?restrictions={\"age\":\"21\"}", new Dictionary<string, string>());
                }
            }
            return RedirectToAction("Accounts");
        }

        public ActionResult DownloadInsights()
        {
            if (!string.IsNullOrEmpty(Request["AccountId"]))
            {
                var facebookApi = new FacebookApi();
                var accountId = long.Parse(Request["AccountId"]);
                var account = facebookApi.User.GetCurrentUser().Accounts.FirstOrDefault(x => x.Id == accountId);
                if (account != null)
                {
                    string accessToken = account.AccessToken;
                    if (account.Category == "Application")
                    {
                        accessToken = facebookApi.Application.GetApplicationAccessToken(accountId.ToString(NumberFormatInfo.InvariantInfo), Request["AppSecret"]);
                    }
                    var core = new FacebookCore { AccessToken = accessToken };
                    var tpc = new TypedGraphClient<string>(core, (x) => x);
                    var result = tpc.MakeGraphPost(accountId.ToString(NumberFormatInfo.InvariantInfo), new Dictionary<string, string> { { "restrictions", "{\"type\":\"alcohol\"}" } });
                    if (result == "true")
                    {
                        Trace.Write("true, posted successfully");
                    }

                    //dynamic accountDetails = accountFacebookApi.GraphApi.MakeGraphPost(accountId.ToString(NumberFormatInfo.InvariantInfo) +  "?restrictions={\"age\":\"21\"}", new Dictionary<string, string>());
                }
            }
            return RedirectToAction("DownloadInsights");
        }

        public ActionResult AccountDetails()
        {
            if(!string.IsNullOrEmpty(Request["AccountId"]))
            {
                var facebookApi = new FacebookApi();
                var accountId = long.Parse(Request["AccountId"]);
                var account = facebookApi.User.GetCurrentUser().Accounts.Where(x => x.Id == accountId).FirstOrDefault();
                if (account != null)
                {
                    var accountFacebookApi = new FacebookApi(account.AccessToken);
                    dynamic accountDetails = accountFacebookApi.GraphApi.MakeGraphRequest(accountId.ToString(NumberFormatInfo.InvariantInfo));
                    return View(accountDetails);
                }
            }
            return RedirectToAction("Accounts");
        }


        public ActionResult AccountPublishExecute()
        {
            
            if (!string.IsNullOrEmpty(Request["AccountId"]) && !string.IsNullOrEmpty(Request["Message"]))
            {
                var facebookApi = new FacebookApi();
                var accountId = long.Parse(Request["AccountId"]);
                var account = facebookApi.User.GetCurrentUser().Accounts.Where(x => x.Id == accountId).FirstOrDefault();
                if (account != null)
                {
                    var accountFacebookApi = new FacebookApi(account.AccessToken);
                    accountFacebookApi.Feed.Publish(
                        account.Id.ToString(),
                        Request["Message"],
                        "http://download.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=facesharp&DownloadId=140644&Build=17027",
                        "http://facesharp.codeplex.com",
                        "FaceSharp",
                        "The .NET Facebook Starter Kit",
                        "Get started with Facebook Development Today!"
                        );
                }
           }
            return RedirectToAction("Accounts");
        }

        public ActionResult Likes()
        {
            var facebookApi = new FacebookApi();
            var likes = facebookApi.Likes.Get(facebookApi.User.GetCurrentUserId());
            ViewData["ApplicationId"] = System.Web.HttpContext.Current.Items["ApplicationId"];
            var likesApp = (likes.Where(x => x.Id == long.Parse(ViewData["ApplicationId"].ToString())).FirstOrDefault() != null);
            ViewData["LikesApp"] = likesApp;
            return View();
        }

        public ActionResult Notifications()
        {
            return View();
        }

        public ActionResult NotificationsSendEmailExecute()
        {
            var facebookApi = new FacebookApi();
            facebookApi.Notifications.SendEmail(facebookApi.User.GetCurrentUserId().ToString(), "FaceSharp test email", "Test email sent from FaceSharp", "");
            return RedirectToAction("Notifications");
        }

        public ActionResult DashboardDecrementCount(long? id)
        {
            var facebookApi = new FacebookApi();
            if (id.HasValue && id.GetValueOrDefault(0) > 0)
            {
              //  graphApi.DashboardDecrementCount(id.GetValueOrDefault(0));
            }
            else
            {
                facebookApi.Dashboard.DecrementCount();
            }

            return RedirectToAction("Dashboard");
        }

        public ActionResult DashboardIncrementCount(long? id)
        {
            var facebookApi = new FacebookApi();
            if(id.HasValue && id.GetValueOrDefault(0) > 0)
            {
                facebookApi.Dashboard.IncrementCount(id.GetValueOrDefault(0)); 
            }
            else
            {
                facebookApi.Dashboard.IncrementCount(); 
            }
            
            return RedirectToAction("Dashboard");
        }

        public ActionResult Places()
        {
            var facebookApi = new FacebookApi();
            ViewData["MyCheckins"] = facebookApi.Places.GetItemCheckins(facebookApi.User.GetCurrentUserId());
            ViewData["RecentCheckins"] = facebookApi.Places.GetRecentCheckins();
            return View();
        }

        public ActionResult Events()
        {
            var facebookApi = new FacebookApi();
            ViewData["MyEvents"] = facebookApi.Events.List("me");
            return View();
        }

		public ActionResult Event(long id)
		{
			var facebookApi = new FacebookApi();
			var myEvent = facebookApi.Events.Get(id);			
			return View(myEvent);
		}

        public ActionResult FeedPublish()
        {
            var facebookApi = new FacebookApi();
            ViewData["ApplicationId"] = System.Web.HttpContext.Current.Items["ApplicationId"];
            var likes = facebookApi.Likes.Get(facebookApi.User.GetCurrentUserId());
            var likesApp = (likes.Where(x => x.Id == long.Parse(ViewData["ApplicationId"].ToString())).FirstOrDefault() != null);
            ViewData["LikesApp"] = likesApp;
            var friends = facebookApi.User.GetFriends();
            return View(friends);
        }

        public ActionResult FeedPublishExecute()
        {
            var facebookApi = new FacebookApi();
            var message = Request.Form["Message"];
            var toUserId = (long.Parse(Request.Form["ToUserId"] ?? "0")) ;
            toUserId = toUserId == 0 ? facebookApi.User.GetCurrentUserId() : toUserId;

            facebookApi.Feed.Publish(
                toUserId.ToString(), 
                message,
                (String.Format("{0}://{1}/{2}", Request.Url.Scheme, Request.Url.Authority, "areas/facebookapp/images/logo-facesharp.gif")),
                "http://facesharp.codeplex.com",
                "FaceSharp",
                "The .NET Facebook Starter Kit",
                "Get started with Facebook Development Today!"
                );
            return RedirectToAction("FeedPublish");
        }

        public ActionResult FeedPublishFlashExecute()
        {
            var facebookApi = new FacebookApi();
            var message = Request.Form["Message"];
            var toUserId = (long.Parse(Request.Form["ToUserId"] ?? "0"));
            toUserId = toUserId == 0 ? facebookApi.User.GetCurrentUserId() : toUserId;

            facebookApi.Feed.Publish(
                toUserId.ToString(),
                message,
                (String.Format("{0}://{1}/{2}", Request.Url.Scheme, Request.Url.Authority, "areas/facebookapp/images/logo-facesharp.gif")),
                "http://facesharp.codeplex.com",
                "FaceSharp",
                "The .NET Facebook Starter Kit",
                "Get started with Facebook Development Today!",
                (String.Format("{0}://{1}/{2}", Request.Url.Scheme, Request.Url.Authority, "content/flash/test.swf?" + message.Trim())) // 
                );
            return RedirectToAction("FeedPublish");
        }

        public ActionResult FeedPublishFlashFriendExecute()
        {
            var facebookApi = new FacebookApi();
            var message = Request.Form["Message"];
            var toUserId = (long.Parse(Request.Form["ToUserId"] ?? "0"));
            toUserId = toUserId == 0 ? facebookApi.User.GetCurrentUserId() : toUserId;

            facebookApi.Feed.Publish(
                toUserId.ToString(),
                message,
                (String.Format("{0}://{1}/{2}", Request.Url.Scheme, Request.Url.Authority, "areas/facebookapp/images/logo-facesharp.gif")),
                "http://facesharp.codeplex.com",
                "FaceSharp",
                "The .NET Facebook Starter Kit",
                "Get started with Facebook Development Today!",
                (String.Format("{0}://{1}/{2}", Request.Url.Scheme, Request.Url.Authority, "content/flash/test.swf?" + message.Trim())) // 
                );
            return RedirectToAction("FeedPublish");
        }

        public ActionResult Dashboard()
        {
            var facebookApi = new FacebookApi();
            var friends = facebookApi.User.GetFriends();
            return View(friends);
        }

        public ActionResult Status()
        {
            return View();
        }

        public ActionResult SetStatus(string status)
        {
            var facebookApi = new FacebookApi();
            facebookApi.User.SetStatus(facebookApi.User.GetCurrentUserId(), status);
            return RedirectToAction("Status");
        }

        public ActionResult Groups()
        {
            var facebookApi = new FacebookApi();            
            ViewData["MyGroups"] = facebookApi.Groups.List("me");
            return View();
        }

        public ActionResult Group(long id)
        {
            var facebookApi = new FacebookApi();
            var myGroup = facebookApi.Groups.Get(id);
            return View(myGroup);
        }

        public ActionResult GroupMembers(long id)
        {
            var facebookApi = new FacebookApi();
            ViewData["GroupMembers"] = facebookApi.Groups.GetMembers(id.ToString());
            return View();
        }

        public ActionResult Links()
        {
            var facebookApi = new FacebookApi();
            ViewData["MyLinks"] = facebookApi.Links.List("me");
            return View();            
        }

        public ActionResult Link(long id)
        {
            var facebookApi = new FacebookApi();
            var myLink = facebookApi.Links.Get(id);
            return View(myLink);            
        }
    }
}
